<template>
  <div class="center-section-content">
    <div class="statistics-position-container">
      <div class="statistics-container">
        <div class="control-panel">
          <div class="control-row">
            <div class="control-group">
              <label for="parameter" class="control-group-label">参数：</label>
              <el-select
                v-model="selectedParameter"
                id="parameter"
                placeholder="请选择"
                size="mini"
                class="control-group-select"
              >
                <el-option
                  v-for="item in parameters"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="control-group">
              <el-button
                type="primary"
                size="mini"
                @click="loadData"
                :disabled="isLoading"
                class="control-group-button"
                >加载数据</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click="togglePlay"
                :disabled="!dataLoaded"
                class="control-group-button"
              >
                {{ isPlaying ? "暂停" : "播放" }}
              </el-button>
            </div>
            <div class="control-group">
              <el-date-picker
                class="control-group-date-picker"
                size="mini"
                v-model="startTime"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="getPoints"
                placeholder="选择开始时间"
                :clearable="false"
              >
              </el-date-picker>
              <!--                            <el-date-picker-->
              <!--                                    class="control-group-date-picker"-->
              <!--                                    size="mini"-->
              <!--                                    v-model="daterange"-->
              <!--                                    type="datetimerange"-->
              <!--                                    range-separator="至"-->
              <!--                                    start-placeholder="开始时间"-->
              <!--                                    end-placeholder="结束时间"-->
              <!--                                    :clearable="false">-->
              <!--                            </el-date-picker>-->
            </div>
            <span class="control-group-date-picker-span">至</span>
            <div class="control-group">
              <el-date-picker
                class="control-group-date-picker"
                size="mini"
                v-model="endTime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="getPoints"
                type="datetime"
                placeholder="选择结束时间"
                :clearable="false"
              >
              </el-date-picker>
            </div>
          </div>

          <div class="control-row">
            <input
              type="range"
              v-model="currentTimeIndex"
              :min="0"
              :max="timeSteps.length - 1"
              :disabled="!dataLoaded"
              @input="handleSliderChange"
              class="time-slider"
            />
          </div>
          <div class="control-row last-row">
            <span class="time-display">{{ currentDisplayTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template> 

<script>
import { EventBus } from "../../utils/event-bus";
let that;
export default {
  name: "Center",
  created() {
    that = this;
    EventBus.$on("set-biological-device-type", (message) => {
      this.type = message;
      this.getPoints();
    });
  },
  data() {
    return {
      // datarange:[this.getDefaultStartTime(),this.getDefaultEndTime()],
      timeSteps: [],
      deviceId: "",
      type: "qixiang",
      itemList: [],
      // 参数选择
      selectedParameter: "",
      parameters: {
        // temperature: { name: '温度', unit: '°C',value:'temperature' },
        // humidity: { name: '湿度', unit: '%',value:'humidity' },
        // pm25: { name: 'PM2.5', unit: 'μg/m³',value:'pm25' }
      },
      // 时间选择
      startTime: this.getDefaultStartTime(),
      endTime: this.getDefaultEndTime(),
      // 播放控制
      isPlaying: false,
      playInterval: null,
      currentTimeIndex: 0,

      // 数据状态
      isLoading: false,
      dataLoaded: false,
      heatmapData: {},

      // 模拟数据
      mockData: {},
      // 模拟定位点
      locations: [],
      pointCount: 100,
    };
  },
  computed: {
    // 计算时间步长
    // timeSteps() {
    //     if (!this.startTime || !this.endTime) return [];
    //
    //     const start = new Date(this.startTime);
    //     const end = new Date(this.endTime);
    //     const steps = [];
    //
    //     while (start <= end) {
    //         steps.push(new Date(start));
    //         start.setHours(start.getHours() + 1);
    //     }
    //
    //     return steps;
    // },

    // 当前显示时间
    currentDisplayTime() {
      if (this.timeSteps.length === 0) return "未选择时间范围";
      // return this.formatTime(this.timeSteps[this.currentTimeIndex]);
      return this.timeSteps[this.currentTimeIndex];
    },

    // 当前热力图数据
    currentHeatmapData() {
      if (!this.dataLoaded || !this.timeSteps[this.currentTimeIndex]) return [];

      // const timeKey = this.formatTimeKey(this.timeSteps[this.currentTimeIndex]);
      const timeKey = this.timeSteps[this.currentTimeIndex];
      return this.heatmapData[timeKey] || [];
    },
  },
  mounted() {
    // this.generateMockData();
  },
  methods: {
    getPoints() {
      this.parameters = {};
      this.mockData = {};
      this.$api.environment.getPointList(this.type).then((res) => {
        res.forEach((r, index) => {
          this.parameters[r.pointCode] = {
            name: r.pointName,
            unit: r.varUnit ? r.varUnit : r.pointUnit,
            value: r.pointCode,
          };
          this.getData(r.pointCode, r.pointCode);
        });
        this.selectedParameter = res[0].pointCode;
      });
    },
    getData(id, pointName) {
      this.$api.environment
        .getHistoryList(this.type, this.startTime, this.endTime, pointName)
        .then((res) => {
          this.mockData[id] = res;
        });
    },
    // 加载数据
    async loadData() {
      if (!this.startTime || !this.endTime) {
        alert("请选择时间范围");
        return;
      }

      if (new Date(this.startTime) >= new Date(this.endTime)) {
        alert("结束时间必须大于开始时间");
        return;
      }

      this.isLoading = true;

      try {
        // 模拟API请求
        await this.mockApiRequest();
        this.dataLoaded = true;
        this.currentTimeIndex = 0;
        this.updateHeatmap();
      } catch (error) {
        this.isLoading = false;
        console.error("数据加载失败:", error);
        alert("数据加载失败");
      } finally {
        this.isLoading = false;
      }
    },

    // 模拟API请求
    mockApiRequest() {
      return new Promise((resolve) => {
        setTimeout(() => {
          // 使用预生成的模拟数据
          this.heatmapData = this.mockData[this.selectedParameter];
          this.timeSteps = [];
          Object.keys(this.heatmapData).forEach(function (key) {
            that.timeSteps.push(key);
          });
          resolve();
        }, 1000);
      });
    },

    // 生成模拟数据121.444487,31.147186
    generateMockData() {
      const parameters = ["temperature", "humidity", "pm25"];
      for (let i = 0; i < this.pointCount; i++) {
        const lng = 121.444487 + (Math.random() * 0.15 - 0.075) * 0.1;
        const lat = 31.147186 + (Math.random() * 0.1 - 0.05) * 0.1;
        this.locations.push({
          lng: lng,
          lat: lat,
        });
      }
      parameters.forEach((param) => {
        this.mockData[param] = {};

        // 生成3天的数据，每小时一个点
        const baseDate = new Date(2025, 3, 1); // 2025年4月1日
        for (let day = 0; day < 3; day++) {
          for (let hour = 0; hour < 24; hour++) {
            const date = new Date(baseDate);
            date.setDate(baseDate.getDate() + day);
            date.setHours(hour);

            const timeKey = this.formatTimeKey(date);
            this.mockData[param][timeKey] = this.generatePointsForTime(
              param,
              date
            );
          }
        }
      });
    },

    // 为特定时间生成模拟点数据
    generatePointsForTime(parameter, date) {
      const points = [];
      const hour = date.getHours();
      const day = date.getDate();

      // 生成北京范围内的随机点
      for (let i = 0; i < this.pointCount; i++) {
        // 北京大致经纬度范围
        // const lng = 116.2 + Math.random() * 0.15;
        // const lat = 39.7 + Math.random() * 0.1;

        let value;

        // 根据不同参数生成不同的值模式
        switch (parameter) {
          case "temperature":
            // 温度模拟 - 白天高，晚上低
            value =
              15 +
              15 * Math.sin((hour / 24) * Math.PI * 2) +
              (Math.random() * 5 - 2.5);
            break;
          case "humidity":
            // 湿度模拟 - 早晨高，下午低
            value =
              40 +
              30 * Math.sin(((hour - 6) / 24) * Math.PI * 2) +
              (Math.random() * 10 - 5);
            break;
          case "pm25":
            // PM2.5模拟 - 早晚高峰高
            value =
              50 +
              50 *
                (Math.sin(((hour - 8) / 24) * Math.PI * 2) +
                  Math.sin(((hour - 18) / 24) * Math.PI * 2)) +
              (Math.random() * 20 - 10);
            break;
          default:
            value = Math.random() * 100;
        }

        // 添加一些日变化
        value += (day - 1) * 5;

        points.push({
          // lng: lng,
          // lat: lat,
          lng: this.locations[i].lng,
          lat: this.locations[i].lat,
          value: Math.max(0, value),
        });
      }

      return points;
    },

    // 更新热力图
    updateHeatmap() {
      if (!this.dataLoaded) return;

      const data = {
        data: this.currentHeatmapData.map((point) => ({
          lng: point.lng,
          lat: point.lat,
          count: point.value,
        })),
        max: this.getMaxValue(this.currentHeatmapData),
      };
      EventBus.$emit("sent-heat-map-data", data);
      // this.heatmap.setDataSet(data);

      // 更新地图标题
      this.updateMapTitle();
    },

    // 获取最大值用于热力图渲染
    getMaxValue(points) {
      if (!points || points.length === 0) return 100;

      let max = 0;
      points.forEach((point) => {
        if (point.value > max) max = point.value;
      });

      return max * 1.1; // 留一些余量
    },

    // 播放/暂停
    togglePlay() {
      if (this.isPlaying) {
        this.pausePlayback();
      } else {
        this.startPlayback();
      }
    },

    // 开始播放
    startPlayback() {
      if (this.playInterval) {
        clearInterval(this.playInterval);
      }

      this.isPlaying = true;

      // 如果到了末尾，回到开头
      if (this.currentTimeIndex >= this.timeSteps.length - 1) {
        this.currentTimeIndex = 0;
      }

      this.playInterval = setInterval(() => {
        if (this.currentTimeIndex < this.timeSteps.length - 1) {
          this.currentTimeIndex++;
          this.updateHeatmap();
        } else {
          this.pausePlayback();
        }
      }, 1000); // 每秒一帧
    },

    // 暂停播放
    pausePlayback() {
      this.isPlaying = false;
      if (this.playInterval) {
        clearInterval(this.playInterval);
        this.playInterval = null;
      }
    },

    // 滑块变化处理
    handleSliderChange() {
      this.updateHeatmap();
      if (this.isPlaying) {
        this.pausePlayback();
      }
    },

    // 更新地图标题
    updateMapTitle() {
      const title = `${this.parameters[this.selectedParameter].name}分布 - ${
        this.currentDisplayTime
      }`;
      document.title = title;
    },

    // 格式化时间显示
    formatTime(date) {
      if (!date) return "";
      return `${date.getFullYear()}年${
        date.getMonth() + 1
      }月${date.getDate()}日 ${date.getHours()}时`;
    },

    // 格式化时间键
    formatTimeKey(date) {
      if (!date) return "";
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
        .getHours()
        .toString()
        .padStart(2, "0")}:00`;
    },

    // 获取默认开始时间
    getDefaultStartTime() {
      const date = new Date();
      // date.setMonth(date.getMonth() + 1); // 4月
      date.setDate(date.getDate() - 1);
      // date.setHours(8, 0, 0, 0);
      return this.formatDateTimeLocal(date);
    },

    // 获取默认结束时间
    getDefaultEndTime() {
      const date = new Date();
      // date.setMonth(3); // 4月
      // date.setDate(2);
      // date.setHours(8, 0, 0, 0);
      return this.formatDateTimeLocal(date);
    },

    // 格式化日期时间输入
    formatDateTimeLocal(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始，需要加1
      const day = date.getDate();
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      // return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  watch: {
    // 当参数变化时，如果已加载数据则重新加载
    selectedParameter() {
      if (this.dataLoaded) {
        this.loadData();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.heatmap-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

#map-container {
  flex: 1;
  width: 100%;
}

.control-panel {
  padding: 15px;
}

.control-row {
  display: flex;
  align-items: center;
  margin-top: 10px;
  flex-wrap: wrap;
}

.control-group {
  margin-right: 10px;
  .control-group-select {
    width: 84px;
    /*width: 168px;*/
    ::v-deep .el-input__inner {
      background: transparent;
      border: none;
      color: #07ffe5;
      padding: 0;
    }

    ::v-deep .el-input__suffix {
      right: 0;
      .el-input__suffix-inner {
        .el-select__caret {
          color: #07ffe5;
          &.is-reverse {
            transform: rotateZ(180deg);
          }
        }
      }
    }
  }

  .control-group-date-picker {
    ::v-deep .el-input__inner {
      background: transparent;
      border: none;
      color: #07ffe5;
    }

    ::v-deep .el-input__prefix,
    ::v-deep .el-input__suffix {
      display: none;
    }
    ::v-deep .el-input__inner {
      padding: 0;
    }
  }
}
.control-group-date-picker-span {
  color: #07ffe5;
  padding: 0;
  font-size: 14px;
  margin: 0 10px 0 0;
}
label {
  margin-right: 8px;
  font-weight: bold;
}

select,
input[type="datetime-local"] {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 6px 16px;
  margin-right: 10px;
  background: #a1c4ff;
  color: #073b66;
  border: none;
  border-radius: 12px;
  cursor: pointer;

  &:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  &:hover {
    background: #a1c4ff;
    color: #073b66;
  }
}

button .time-display {
  margin-left: 10px;
  font-weight: bold;
  min-width: 200px;
  font-size: 12px;
}

.time-slider {
  flex: 1;
  min-width: 300px;
  margin: 0 10px;
}
.statistics-position-container {
  position: absolute;
  top: 54px;
  left: 83px;
  z-index: 1000;
  pointer-events: auto;
  width: 79%;
}
.statistics-container {
  color: #07ffe5;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(0, 50, 125, 0.3);
}
.control-group-label {
  font-size: 14px;
  color: #07ffe5;
}
.control-group-select {
  width: 84px;
}
.control-group-date-picker {
  width: 113px;
}
.last-row {
  justify-content: flex-end;
  text-align: right;
  padding-right: 12px;
}
</style>

<style lang="scss">
.el-select-dropdown.el-popper {
  border-radius: 0;
  margin-top: 0;
  margin-bottom: 0;
  background: rgba(0, 50, 125, 0.3);
  border: 1px solid rgba(7, 255, 229, 0.3);
  .el-select-dropdown__wrap {
    margin-bottom: -21px !important;
    margin-top: -7px !important;
  }
  .el-select-dropdown__item {
    color: #07ffe5;
    border-bottom: 1px solid rgba(7, 255, 229, 0.3);
    height: 30px;
    line-height: 30px;
    padding: 0;
    text-align: center;

    &:last-child {
      border-bottom: none;
      height: 30px;
      line-height: 30px;
    }

    &.selected,
    &.hover {
      color: #07ffe5;
      background: rgba(7, 255, 229, 0.1);
    }
  }

  .popper__arrow {
    display: none;
  }
}
</style>
